package nil.ed.simulator.request.biz.qq.listener;

import com.google.inject.Inject;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import nil.ed.simulator.request.enums.events.EventMode;
import nil.ed.simulator.request.enums.events.EventType;
import nil.ed.simulator.request.event.Event;
import nil.ed.simulator.request.event.EventBusAware;
import nil.ed.simulator.request.event.bus.EventBus;
import nil.ed.simulator.request.event.bus.EventListener;
import nil.ed.simulator.request.output.IOutput;
import nil.ed.simulator.request.repo.RuntimeRepo;

import java.io.File;

/**
 * @author lidelin.
 */
@Slf4j
public class ExportCookieListener implements EventListener, EventBusAware {

    private final IOutput output;
    @Setter
    private EventBus eventBus;

    @Inject
    public ExportCookieListener(IOutput output) {
        this.output = output;
    }

    @Override
    public void onEvent(Event event) {
        if (RuntimeRepo.QQ_REPO.isFinish()) {
            File f = (File) event.getData();
            log.info("Start to export cookie...");
            try {
                output.output(f);
                log.info("Succeed to export cookie");
                eventBus.publish(Event.builder()
                        .eventMode(EventMode.SYNC)
                        .eventType(EventType.FILE_EXPORT_SUCCESS)
                        .data(f)
                        .build());
            } catch (Exception e) {
                log.error("Failed to export cookie!", e);
                eventBus.publish(Event.builder()
                        .eventMode(EventMode.SYNC)
                        .eventType(EventType.FILE_EXPORT_FAILED)
                        .data(f)
                        .build());
            }
        }
    }

    @Override
    public boolean isSupport(Event event) {
        return event.getEventType() == EventType.FILE_EXPORT;
    }
}
